package com.zf.rpc.transport.socket.server;

import com.zf.rpc.transport.AbstractRpcServer;

import com.zf.rpc.handler.RequestHandler;
import com.zf.rpc.hook.ShutdownHook;

import com.zf.rpc.provider.ServiceProviderImpl;
import com.zf.rpc.registry.NacosServiceRegistry;

import com.zf.rpc.serializer.CommonSerializer;
import com.zf.rpc.factory.ThreadPoolFactory;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @ProjectName: RPC-zhaofeng
 * @Package: com.zf.simpleImplementation
 * @ClassName: RpcServer
 * @Author: zf
 * @Description:Socket方式远程方法调用的提供者（服务端）
 * @Date: 2021/5/6 23:14
 * @Version: 1.0
 */
public class SocketServer extends AbstractRpcServer {

    private final ExecutorService threadPool;

    private CommonSerializer serializer;
    private RequestHandler requestHandler = new RequestHandler();



    public SocketServer(String host, int port) {
        this(host, port, DEFAULT_SERIALIZER);
    }

    public SocketServer(String host, int port, Integer serializer) {
        this.host = host;
        this.port = port;
        threadPool = ThreadPoolFactory.createDefaultThreadPool("socket-rpc-server");
        this.serviceRegistry = new NacosServiceRegistry();
        this.serviceProvider = new ServiceProviderImpl();
        this.serializer = CommonSerializer.getByCode(serializer);
        scanServices();
    }


    @Override
    public void start() {
        try (ServerSocket serverSocket = new ServerSocket()) {
            serverSocket.bind(new InetSocketAddress(host, port));
            logger.info("服务器正在启动...");
            ShutdownHook.getShutdownHook().addClearAllHook();
            Socket socket;
            while((socket = serverSocket.accept()) != null) {
                logger.info("消费者链接：{}:{}", socket.getInetAddress(),socket.getPort());
                threadPool.execute(new RequestHandlerThread(socket, requestHandler, serviceRegistry, serializer));
            }
            threadPool.shutdown();
        } catch (IOException e) {
            logger.error("服务器启动时有错误发生：", e);
        }
    }


}
